'''
Copyright (C) <2011> by Kevin Klein

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''

from .rpc import Handler
import xml.parsers.expat

class RequestHandler(object):
    VALUE_TYPES = ('i4', 'int', 'string', 'boolean', 'double')
    
    def __init__(self):
        self.method_name = ''
        self.__active = ''
        self.params = []
        
    def start_element(self, name, attrs):
        if name == 'methodName':
            self.__active = name
        elif name == 'param':
            self.__active = name
        elif name == 'value':
            if self.__active != 'param':
                raise RuntimeError('invalid document format')
            self.__active = name
        elif name in RequestHandler.VALUE_TYPES:
            if self.__active != 'value':
                raise RuntimeError('invalid document format')
            self.__active = name
        
    def end_element(self, name):
        if name == 'value':
            self.__active = 'param'
        elif name in RequestHandler.VALUE_TYPES:
            self.__active = 'value'
        
    def char_data(self, data):
        if self.__active == 'methodName':
            self.method_name += str(data.strip())
        elif self.__active in RequestHandler.VALUE_TYPES:
            if self.__active == 'i4' or self.__active == 'int':
                data = int(data)
            elif self.__active == 'string':
                data = string(data)
            elif self.__active == 'double':
                data = float(data)
            elif self.__active == 'boolean':
                if data == '0':
                    data = True
                else:
                    data = False
            else:
                raise RuntimeError('invalid value type')
                
            self.params.append(data)
        
        
body = \
'''
<?xml version="1.0"?>
<methodResponse>
<params>
{0}
</params>
</methodResponse>
'''
def format_scalar(data):
    if type(data) == str:
        return '<value><string>{0}</string></value>'.format(data)
    elif type(data) == float:
        return '<value><double>{0}</double></value>'.format(data)
    elif type(data) == bool:
        data = 1 if data else 0
        return '<value><boolean>{0}</boolean></value>'.format(data)
    elif type(data) == int:
        return '<value><int>{0}</int></value>'.format(data)
    else:
        raise RuntimeError('unkown type: {0}'.format(str(type(data))))

def format_list(data):
    #<array>
    #<data>
    #   <value><i4>12</i4></value>
    #   <value><string>Egypt</string></value>
    #   <value><boolean>0</boolean></value>
    #   <value><i4>-31</i4></value>
    #   </data>
    #</array>
    ret = '<array><data>'
    for item in data:
       ret += format_item(item)
    ret += '</array></data>'
    return ret

def format_dict(data):
    #<struct>
    #<member>
    #<name>lowerBound</name>
    #<value><i4>18</i4></value>
    #</member>
    #<member>
    #<name>upperBound</name>
    #<value><i4>139</i4></value>
    #</member>
    #</struct>
    ret = '<struct><member>'
    for key, value in data.items():
        ret += '<member>'
        ret += '<name>'
        ret += format_item(key)
        ret += '</name>'
        ret += '<value>'
        ret += format_item(value)
        ret += '</value>'
        ret += '</member>'
    ret += '</struct></member>'
    return ret

def format_item(item):
    if type(item) == list:
        return format_list(item)
    elif type(item) == dict:
        return format_dict(item)
    else:
        return format_scalar(item)

def format(*data):
    ret = ''
    for item in data:
        ret += '<param>'
        ret += format_item(item)
        ret += '</param>'
    return body.format(ret)
        
class XMLHandler(Handler):

    '''
    this is version 1.0
    '''
    
    def __init__(self, debug=True):
        Handler.__init__(self, debug)
        self.parser = xml.parsers.expat.ParserCreate()
        self.handler = RequestHandler()
        self.parser.StartElementHandler = self.handler.start_element
        self.parser.EndElementHandler = self.handler.end_element
        self.parser.CharacterDataHandler = self.handler.char_data

    def generate_response(self, args):
        #example:
        #<?xml version="1.0"?>
        #<methodResponse>
        #   <params>
        #      <param>
        #         <value><string>South Dakota</string></value>
        #         </param>
        #      </params>
        #   </methodResponse>
        
        return format(args)
        
    def parse_request(self, data):
        #example: 
        #<?xml version="1.0"?>
        #<methodCall>
        #   <methodName>examples.getStateName</methodName>
        #   <params>
        #      <param>
        #         <value><i4>41</i4></value>
        #         </param>
        #      </params>
        #   </methodCall>
        self.parser.Parse(data)
        return self.handler.method_name, self.handler.params
    
    def render_error(self, name, msg):
        return format({'name': name, 'message': msg})
        
    def validate(self, request):
        return (True, '', '')
        
